package com.example.cardgame

import android.os.Bundle
import androidx.gridlayout.widget.GridLayout
import android.content.Intent
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.view.children
import com.example.cardgame.model.CardMatchingGame
import java.util.Locale

class ThirdActivity : AppCompatActivity(),View.OnClickListener {

    private lateinit var game: CardMatchingGame
    private val cardButtons = mutableListOf<Button>()
    private var highScore: Int = 0;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main3)
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
//            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
//            insets
//        }
        val reset = findViewById<Button>(R.id.button6)
        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)

        for (v in gridLayout.children){
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        if(game.score>highScore){
            highScore=game.score
        }

        val button2 = findViewById<Button>(R.id.button7)
        button2.setOnClickListener {

            val intent = Intent(this, MainActivity::class.java).apply {
                putExtra("HIGH_SCORE", highScore) // 通过Intent传递最高分
            }
            startActivity(intent)
        }
    }

    private fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen){
                button.text = card.toString()
                button.setBackgroundColor(Color.White.toArgb())
            }else{
                button.text = ""
                button.setBackgroundResource(R.drawable.blue)
            }
        }
        val score = findViewById<TextView>(R.id.textView3)
        score.text = String.format(Locale.getDefault(),"%d",game.score)

        if(game.score>highScore){
            highScore=game.score
        }
    }


    override fun onClick(v: View?) {
        if(v is Button) {
            val index = cardButtons.indexOf(v)
            if (index != -1) {
                game.chooseCardAtIndex(index)
                updateUI()
            }
        }
    }
}